import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/model/exam.dart';
import 'package:kxy_flutter_app/view/examination/correct_ques_view.dart';
import 'package:provider/provider.dart';
import 'exam_result/exam_result_view.dart';
import 'view_model/exam_model.dart';
import 'widget/countdown_model.dart';
import 'widget/countdown_widget.dart';
import 'widget/exam_bottom_bar_widget.dart';
import 'widget/question_header_widget.dart';
import 'widget/question_swiper_widget.dart';

class DoExamView extends StatefulWidget {
  final Exam exam;

  const DoExamView({Key key, @required this.exam}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return DoExamViewState();
  }
}

class DoExamViewState extends State<DoExamView> {
  SwiperController swiperCtrl = new SwiperController();
  ExamModel examModel;
  CountdownModel countdownModel;
  bool isLoaded = false;

  @override
  void didChangeDependencies() {
    startExam();
    super.didChangeDependencies();
  }

  Future startExam() async {
    if (!isLoaded) {
      examModel = Provider.of<ExamModel>(context);
      await examModel.startExam(widget.exam);
      countdownModel = new CountdownModel(
        isStop: false,
        seconds: examModel.duration,
        submitPaper: () => this.submitPaper(force: true),
      );
      isLoaded = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoaded) {
      if (examModel.questionList.length == 0) {
        return Scaffold(
          appBar: AppBar(title: Text('开始考试')),
          body: Center(
            child: Text('没有试题!'),
          ),
        );
      }

      return WillPopScope(
        child: Scaffold(
          backgroundColor: Colors.white,
          appBar: appBar(),
          body: Column(
            children: [
              QuestionHeaderWidget(
                question: examModel.current,
                index: examModel.index,
                total: examModel.questionList.length,
              ),
              Expanded(
                child: QuestionSwiperWidget(
                  swiperCtrl: swiperCtrl,
                  setAnswer: examModel.setAnswer,
                  questionList: examModel.questionList,
                  onChangeIndex: examModel.changeIndex,
                ),
              ),
            ],
          ),
          bottomNavigationBar: ExamBottomBarWidget(
            swiperCtrl: swiperCtrl,
            submitPaper: submitPaper,
          ),
        ),
        onWillPop: () async {
          await submitPaper();
          return Future.value(true);
        },
      );
    }

    return Scaffold(
      appBar: AppBar(title: Text('开始考试')),
      body: LoadingWidget(),
    );
  }

  Widget appBar() {
    if (countdownModel == null || countdownModel.seconds < 0) {
      return AppBar(
        title: Text('无限时长'),
        centerTitle: true,
        actions: [correctionWidget()],
      );
    }
    return AppBar(
      centerTitle: true,
      elevation: 0,
      title: countdownModel == null ? Container() : CountdownWidget(countdownModel: countdownModel),
      actions: [correctionWidget()],
    );
  }

  Future submitPaper({bool force = false}) async {
    if (force == true) {
      countdownModel.isStop = true;
      var success = await examModel.submitPaper(countdownModel.seconds);
      if (success) {
        Navigator.popUntil(context, (route) => route.isCurrent);
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (cxt) => ExamResultView(),
          ),
          result: examModel.examResult.isPass,
        );
      }
    } else {
      showConfirmSubmitPaperDialog();
    }
  }

  Widget correctionWidget() {
    return FlatButton(
      textColor: Theme.of(context).primaryColor,
      child: Text('纠错'),
      onPressed: () {
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (cxt) => CorrectQuesView(quesId: examModel.current.quesId),
          ),
        );
      },
    );
  }

  void showConfirmSubmitPaperDialog() {
    showDialog(
      context: context,
      child: AlertDialog(
        title: Text('提示'),
        content: examModel.isComplete ? Text('您确认交卷吗？') : Text('您还未完成考试，您确认交卷吗？'),
        actions: [
          FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              }),
          FlatButton(
              child: Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
                submitPaper(force: true);
              }),
        ],
      ),
    );
  }
}
